package org.example.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class RedisLock 
{
	private String name;
	private RedisTemplate redisTemplate;


	private static final String ID_PREFIX = UUID.randomUUID().toString()+"-";
	private static final String KEY_PREFIX = "lock:";
	
//	private static final Integer EXPIRE = 30;

	public RedisLock(String name, RedisTemplate redisTemplate) {
		this.name = name;
		this.redisTemplate = redisTemplate;
	}

	//上锁
	public boolean locked(long time)
	{
		long id = Thread.currentThread().getId();
		String threadId = ID_PREFIX + id;
		String key = KEY_PREFIX + name;
		Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, threadId, time, TimeUnit.SECONDS);
		return aBoolean;
	}

	/**
	 * 使用lua脚本处理，达到原子性操作
	 */
	//返回值Long类型
	private static final RedisScript<Long> REDIS_SCRIPT;
	
	static {
		REDIS_SCRIPT = RedisScript.of(
				new ClassPathResource("script/unlock.lua"),
				Long.class
		);
	}
	
	
	//解锁
//	public void unlock()
//	{
//		String key = KEY_PREFIX + name;
//		long id = Thread.currentThread().getId();
//		String threadId = ID_PREFIX + id;
//		String s = (String)redisTemplate.opsForValue().get(key);
//		if(threadId.equals(s))	//如果相等就可以删除
//		{
//			redisTemplate.delete(key);
//		}
//	}

	/**
	 * 使用lua脚本执行，保证原子性问题
	 */
	public void unlock()
	{
		String key = KEY_PREFIX + name;
		long id = Thread.currentThread().getId();
		String threadId = ID_PREFIX + id;
		//执行lua脚本
		redisTemplate.execute(
				REDIS_SCRIPT,
				Arrays.asList(key),
				threadId);
	}
}
